import React, { Component } from 'react'
import { FormattedMessage, injectIntl } from 'react-intl';
import { actions } from "mirrorx";
import { InputNumber, Select, FormControl, Table, Message } from "tinper-bee";
import Radio from 'bee-radio';
import moment from 'moment'
import DatePicker from "bee-datepicker";
import SearchPanel from 'components/SearchPanel';
import RefComponent from 'components/RefComponent';
import FormList from 'components/FormList'
import FormError from 'components/FormError';
import { deepClone, getValidateFieldsTrim, initValueString,onHandleChildObj } from "utils";

import { searchField } from '../InitTemplate';
import zhCN from "rc-calendar/lib/locale/zh_CN";

let { RangePicker } = DatePicker;

import './index.less'

const FormItem = FormList.Item;
const { Option } = Select;
const format = "YYYY";
const { YearPicker } = DatePicker;

class SearchAreaForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refStateParam: {}
        }

    }
    /** 查询数据
     * @param {*} error 校验是否成功
     * @param {*} values 表单数据
     */
    search = () => {
        this.props.form.validateFields((err, _values) => {
            // if(!_values.dept || !JSON.parse(_values.dept).refpk) {
            //     Message.create({ content: '必输项未填', color: 'warning', duration: 10 });
            //     return;
            // }
            let values = getValidateFieldsTrim(_values);

            for (let attr in values) {
                if (values[attr] == null || values[attr] == "")
                    delete values[attr];
            }

            this.getQuery(values, 0);
        });

    }


    /**
     * 重置 如果无法清空，请手动清空
     */
    reset = () => {
        let param = {};
        let _this = this;
        searchField.map(item => {
            param[item.enname] = ""
            _this.props.form.setFieldsValue(param);
        })
    }


    /** 查询数据
     * @param {Object} values 表单对象
     * @param {Number} type 1位清空操作，0位查询操作
     */
    getQuery = (values, type) => {
        let queryParam = deepClone(this.props.queryParam);
        // queryParam.pageParams.pageIndex = 0;
        // queryParam.pageParams.pageSize = 10;
        queryParam.whereParams = values;
        actions.PurchaseOrderTraceForm.updateState(queryParam);
        if (type === 0) {
            actions.PurchaseOrderTraceForm.loadList(queryParam);
        }
    }

    //拼接下级级联的上级参数值
    calcuParm = (item, data, fieldName, childType) => {
        let { refStateParam } = this.state;
        let tempParam = {};
        let cascadeName = item.cascadeName;
        // let param = item.param;
        // if(!param)  param={};
        if (!cascadeName) return param;
        //待优化 先取一个级联参数
        let paramName = cascadeName[0];

        tempParam[paramName] = data[0] && data[0].refpk || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        let _thisParmField = `${fieldName}_${childType}`;
        refStateParam[_thisParmField] = tempParam;
        this.setState({ refStateParam });
    }
    //重置下级级联参照
    resetOfferRef = (item, childType, childRowData) => {
        if (!item.offers) return;
        let param = {}
        param[item.offers] = null;
        //重置级联下级参照值
        this.props.form.setFieldsValue(param);
    }

    renderFunc = (flag) => {
        let { queryParam, selectDataList = {} } = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let dom = [];
        let childRowData = queryParam.whereParams;
        let self = this;
        let childType = "DataHeader";
        searchField.forEach((item, index) => {
            if (flag == 1 && index > 2) {
                return false;
            }
            if (flag == 2 && index < 3) {
                return true;
            }
            switch (item.type) {
                case 'FormControl':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        label={item.zhname}
                    >
                        <FormControl
                            key={`${item.enname}${index}`}
                            disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || "",
                            })}
                        />
                    </FormItem>);
                    break;
                case 'InputNumber':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        label={item.zhname}
                    >
                        <InputNumber toThousands={true} 
                            key={`${item.enname}${index}`}
                            iconStyle="one" step={1} disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: (typeof childRowData[item.enname]) === "number" ? childRowData[item.enname] : -1,
                                rules: [{ required: true }],
                                pattern: /^[0-9]+(.[0-9]{1,8})?$/
                            })}
                        />
                    </FormItem>);
                    break;
                case 'DatePicker':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        label={item.zhname}
                    >
                        <DatePicker
                            key={`${item.enname}${index}`}
                            format={item.format || format} disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] && moment(childRowData[item.enname]) || moment(),
                                validateTrigger: 'onBlur',
                                rules: [{ required: false, message: '请选择领取时间', }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RangePicker':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        label={item.zhname}
                    >
                        <RangePicker
                            key={`${item.enname}${index}`}
                            disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || [moment(), moment()],
                                validateTrigger: 'onBlur',
                                rules: [{ required: false, message: '请选择领取时间', }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RefComponent':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        label={item.zhname}
                    >
                        <RefComponent
                            key={`${item.enname}${index}`}
                            constparam={item.param}
                            aliasparam={self.state.refStateParam}
                            aliasfieldName={item.alias}
                            title={item.zhname}
                            refName={item.refname}
                            childType={childType}
                            fieldName={item.enname}
                            clearMatchData={this.clearMatch}
                            initialValue={initValueString(
                                childRowData[item.showname],
                                childRowData[item.enname],
                                item.required,
                                childRowData[item.codename],
                            )}
                            refTableOnClickSave={(refName, fieldName, data) => {
                               
                            }}
                            form={self.props.form}
                        />
                    </FormItem>);
                    break;
                case 'Select':
                    let options = selectDataList[item.code] || item.options;
                    dom.push(<FormItem
                        className="time"

                        required={item.required}
                        label={item.zhname}
                    >
                        <Select
                            key={`${item.enname}${index}`}
                            disabled={!item.edit}
                            {
                            ...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || "",
                            })
                            }
                        >
                            <Option value="">请选择</Option>
                            {
                                options && options.map((item, index) => {
                                    return (
                                        <Option key={index} value={item.code}>{item.name}</Option>
                                    )
                                })
                            }

                        </Select>
                        <FormError errorMsg={getFieldError(`${item.enname}`)} />
                    </FormItem>);
                    break;
                case 'Radio':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        label={item.zhname}
                    >
                        <Radio.RadioGroup
                            key={`${item.enname}${index}`}
                            disabled={!item.edit}
                            {
                            ...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || '1',
                            }
                            )}
                        >
                            {
                                item.options && item.options.map((itemoption, index) => {
                                    return (
                                        <Radio
                                            disabled={!item.edit}
                                            key={index} value={itemoption.key}>{itemoption.value}</Radio>
                                    )
                                })
                            }
                        </Radio.RadioGroup>
                        <FormError errorMsg={getFieldError(`${item.enname}`)} />
                    </FormItem>);
                    break;
                default: break;
            }
        })
        return dom;
    }


    render() {
        let { form, onCallback } = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let self = this;
        let headchildren = <FormList size="sm">
            {self.renderFunc(1)}

        </FormList>
        return (
            <SearchPanel
                form={form}
                reset={this.reset}
                onCallback={onCallback}
                intl={this.props.intl}
                search={this.search}
                headchildren={headchildren}>
                <FormList size="sm">
                    {self.renderFunc(2)}
                </FormList>
            </SearchPanel>
        )
    }
}

export default FormList.createForm()(injectIntl(SearchAreaForm))
